<!DOCTYPE html>
<html lang="zh-CN">
    <!-- title -->




<!-- keywords -->




<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" >
    <meta name="author" content="宇航猫休蛰">
    <meta name="renderer" content="webkit">
    <meta name="copyright" content="宇航猫休蛰">
    
    <meta name="keywords" content="hexo,hexo-theme,hexo-blog">
    
    <meta name="description" content="">
    <meta name="description" content="torch.nn其是专门为深度学习而设计的模块。torch.nn的核心数据结构是Module，它是一个抽象概念，既可以表示神经网络中的某个层（layer），也可以表示一个包含很多层的神经网络。在实际使用中，最常见的做法是继承nn.Module，撰写自己的网络&#x2F;层。 本节主要参考资料为：apacheCN的pytorch文档、ShusenTang改写的pytorch版《动手学深度学习》和陈云的《深度学">
<meta property="og:type" content="article">
<meta property="og:title" content="pytorch学习第三课：神经网络工具箱Torch.nn">
<meta property="og:url" content="http://xiuzhedorothy.gitee.io/2020/02/01/pytorch-xue-xi-di-san-ke-shen-jing-wang-luo-gong-ju-xiang-torch-nn/index.html">
<meta property="og:site_name" content="休蛰的笔记本">
<meta property="og:description" content="torch.nn其是专门为深度学习而设计的模块。torch.nn的核心数据结构是Module，它是一个抽象概念，既可以表示神经网络中的某个层（layer），也可以表示一个包含很多层的神经网络。在实际使用中，最常见的做法是继承nn.Module，撰写自己的网络&#x2F;层。 本节主要参考资料为：apacheCN的pytorch文档、ShusenTang改写的pytorch版《动手学深度学习》和陈云的《深度学">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-02-01T08:40:09.000Z">
<meta property="article:modified_time" content="2020-03-01T13:22:28.649Z">
<meta property="article:author" content="宇航猫休蛰">
<meta property="article:tag" content="深度学习">
<meta property="article:tag" content="pytorch">
<meta name="twitter:card" content="summary">
    <meta http-equiv="Cache-control" content="no-cache">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    
    <link rel="alternate" href="/atom.xml" title="宇航猫的笔记本" type="application/atom+xml">
    
    <title>pytorch学习第三课：神经网络工具箱Torch.nn · 宇航猫的笔记本</title>
    <style type="text/css">
    @font-face {
        font-family: 'Oswald-Regular';
        src: url("/font/Oswald-Regular.ttf");
    }

    body {
        margin: 0;
    }

    header,
    footer,
    .back-top,
    .sidebar,
    .container,
    .site-intro-meta,
    .toc-wrapper {
        display: none;
    }

    .site-intro {
        position: relative;
        z-index: 3;
        width: 100%;
        /* height: 50vh; */
        overflow: hidden;
    }

    .site-intro-placeholder {
        position: absolute;
        z-index: -2;
        top: 0;
        left: 0;
        width: calc(100% + 300px);
        height: 100%;
        background: repeating-linear-gradient(-45deg, #444 0, #444 80px, #333 80px, #333 160px);
        background-position: center center;
        transform: translate3d(-226px, 0, 0);
        animation: gradient-move 2.5s ease-out 0s infinite;
    }

    @keyframes gradient-move {
        0% {
            transform: translate3d(-226px, 0, 0);
        }
        100% {
            transform: translate3d(0, 0, 0);
        }
    }

</style>

    <link rel="preload" href= "/css/style.css?v=20180824" as="style" onload="this.onload=null;this.rel='stylesheet'" />
    <link rel="stylesheet" href= "/css/mobile.css?v=20180824" media="(max-width: 980px)">
    
    <link rel="preload" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.2.5/jquery.fancybox.min.css" as="style" onload="this.onload=null;this.rel='stylesheet'" />
    
    <!-- /*! loadCSS. [c]2017 Filament Group, Inc. MIT License */
/* This file is meant as a standalone workflow for
- testing support for link[rel=preload]
- enabling async CSS loading in browsers that do not support rel=preload
- applying rel preload css once loaded, whether supported or not.
*/ -->
<script>
(function( w ){
	"use strict";
	// rel=preload support test
	if( !w.loadCSS ){
		w.loadCSS = function(){};
	}
	// define on the loadCSS obj
	var rp = loadCSS.relpreload = {};
	// rel=preload feature support test
	// runs once and returns a function for compat purposes
	rp.support = (function(){
		var ret;
		try {
			ret = w.document.createElement( "link" ).relList.supports( "preload" );
		} catch (e) {
			ret = false;
		}
		return function(){
			return ret;
		};
	})();

	// if preload isn't supported, get an asynchronous load by using a non-matching media attribute
	// then change that media back to its intended value on load
	rp.bindMediaToggle = function( link ){
		// remember existing media attr for ultimate state, or default to 'all'
		var finalMedia = link.media || "all";

		function enableStylesheet(){
			link.media = finalMedia;
		}

		// bind load handlers to enable media
		if( link.addEventListener ){
			link.addEventListener( "load", enableStylesheet );
		} else if( link.attachEvent ){
			link.attachEvent( "onload", enableStylesheet );
		}

		// Set rel and non-applicable media type to start an async request
		// note: timeout allows this to happen async to let rendering continue in IE
		setTimeout(function(){
			link.rel = "stylesheet";
			link.media = "only x";
		});
		// also enable media after 3 seconds,
		// which will catch very old browsers (android 2.x, old firefox) that don't support onload on link
		setTimeout( enableStylesheet, 3000 );
	};

	// loop through link elements in DOM
	rp.poly = function(){
		// double check this to prevent external calls from running
		if( rp.support() ){
			return;
		}
		var links = w.document.getElementsByTagName( "link" );
		for( var i = 0; i < links.length; i++ ){
			var link = links[ i ];
			// qualify links to those with rel=preload and as=style attrs
			if( link.rel === "preload" && link.getAttribute( "as" ) === "style" && !link.getAttribute( "data-loadcss" ) ){
				// prevent rerunning on link
				link.setAttribute( "data-loadcss", true );
				// bind listeners to toggle media back
				rp.bindMediaToggle( link );
			}
		}
	};

	// if unsupported, run the polyfill
	if( !rp.support() ){
		// run once at least
		rp.poly();

		// rerun poly on an interval until onload
		var run = w.setInterval( rp.poly, 500 );
		if( w.addEventListener ){
			w.addEventListener( "load", function(){
				rp.poly();
				w.clearInterval( run );
			} );
		} else if( w.attachEvent ){
			w.attachEvent( "onload", function(){
				rp.poly();
				w.clearInterval( run );
			} );
		}
	}


	// commonjs
	if( typeof exports !== "undefined" ){
		exports.loadCSS = loadCSS;
	}
	else {
		w.loadCSS = loadCSS;
	}
}( typeof global !== "undefined" ? global : this ) );
</script>

    <link rel="icon" href= "/assets/favicon.ico" />
    <link rel="preload" href="https://cdn.jsdelivr.net/npm/webfontloader@1.6.28/webfontloader.min.js" as="script" />
    <link rel="preload" href="https://cdn.jsdelivr.net/npm/jquery@3.3.1/dist/jquery.min.js" as="script" />
    <link rel="preload" href="/scripts/main.js" as="script" />
    <link rel="preload" as="font" href="/font/Oswald-Regular.ttf" crossorigin>
    <link rel="preload" as="font" href="https://at.alicdn.com/t/font_327081_1dta1rlogw17zaor.woff" crossorigin>
    
    <!-- fancybox -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.2.5/jquery.fancybox.min.js" defer></script>
    <!-- 百度统计  -->
    
    <!-- 谷歌统计  -->
    
<meta name="generator" content="Hexo 4.2.0"><link rel="stylesheet" href="/css/prism.css" type="text/css"></head>

    
        <body class="post-body">
    
    
<header class="header">

    <div class="read-progress"></div>
    <div class="header-sidebar-menu">&#xe775;</div>
    <!-- post页的toggle banner  -->
    
    <div class="banner">
            <div class="blog-title">
                <a href="/" >宇航猫的笔记本</a>
            </div>
            <div class="post-title">
                <a href="#" class="post-name">pytorch学习第三课：神经网络工具箱Torch.nn</a>
            </div>
    </div>
    
    <a class="home-link" href=/>宇航猫的笔记本</a>
</header>
    <div class="wrapper">
        <div class="site-intro" style="







height:50vh;
">
    
    <!-- 主页  -->
    
    
    <!-- 404页  -->
            
    <div class="site-intro-placeholder"></div>
    <div class="site-intro-img" style="background-image: url(/intro/post-bg.jpg)"></div>
    <div class="site-intro-meta">
        <!-- 标题  -->
        <h1 class="intro-title">
            <!-- 主页  -->
            
            pytorch学习第三课：神经网络工具箱Torch.nn
            <!-- 404 -->
            
        </h1>
        <!-- 副标题 -->
        <p class="intro-subtitle">
            <!-- 主页副标题  -->
            
            
            <!-- 404 -->
            
        </p>
        <!-- 文章页meta -->
        
            <div class="post-intros">
                <!-- 文章页标签  -->
                
                    <div class= post-intro-tags >
    
        <a class="post-tag" href="javascript:void(0);" data-tags = "深度学习">深度学习</a>
    
        <a class="post-tag" href="javascript:void(0);" data-tags = "pytorch">pytorch</a>
    
</div>
                
                
                    <div class="post-intro-read">
                        <span>字数统计: <span class="post-count word-count">1.7k</span>阅读时长: <span class="post-count reading-time">6 min</span></span>
                    </div>
                
                <div class="post-intro-meta">
                    <span class="post-intro-calander iconfont-archer">&#xe676;</span>
                    <span class="post-intro-time">2020/02/01</span>
                    
                    <span id="busuanzi_container_page_pv" class="busuanzi-pv">
                        <span class="iconfont-archer">&#xe602;</span>
                        <span id="busuanzi_value_page_pv"></span>
                    </span>
                    
                    <span class="shareWrapper">
                        <span class="iconfont-archer shareIcon">&#xe71d;</span>
                        <span class="shareText">Share</span>
                        <ul class="shareList">
                            <li class="iconfont-archer share-qr" data-type="qr">&#xe75b;
                                <div class="share-qrcode"></div>
                            </li>
                            <li class="iconfont-archer" data-type="weibo">&#xe619;</li>
                            <li class="iconfont-archer" data-type="qzone">&#xe62e;</li>
                            <li class="iconfont-archer" data-type="twitter">&#xe634;</li>
                            <li class="iconfont-archer" data-type="facebook">&#xe67a;</li>
                        </ul>
                    </span>
                </div>
            </div>
        
    </div>
</div>
        <script>
 
  // get user agent
  var browser = {
    versions: function () {
      var u = window.navigator.userAgent;
      return {
        userAgent: u,
        trident: u.indexOf('Trident') > -1, //IE内核
        presto: u.indexOf('Presto') > -1, //opera内核
        webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
        gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
        mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
        ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
        android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
        iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者安卓QQ浏览器
        iPad: u.indexOf('iPad') > -1, //是否为iPad
        webApp: u.indexOf('Safari') == -1, //是否为web应用程序，没有头部与底部
        weixin: u.indexOf('MicroMessenger') == -1, //是否为微信浏览器
        uc: u.indexOf('UCBrowser') > -1 //是否为android下的UC浏览器
      };
    }()
  }
  console.log("userAgent:" + browser.versions.userAgent);

  // callback
  function fontLoaded() {
    console.log('font loaded');
    if (document.getElementsByClassName('site-intro-meta')) {
      document.getElementsByClassName('intro-title')[0].classList.add('intro-fade-in');
      document.getElementsByClassName('intro-subtitle')[0].classList.add('intro-fade-in');
      var postIntros = document.getElementsByClassName('post-intros')[0]
      if (postIntros) {
        postIntros.classList.add('post-fade-in');
      }
    }
  }

  // UC不支持跨域，所以直接显示
  function asyncCb(){
    if (browser.versions.uc) {
      console.log("UCBrowser");
      fontLoaded();
    } else {
      WebFont.load({
        custom: {
          families: ['Oswald-Regular']
        },
        loading: function () {  //所有字体开始加载
          // console.log('loading');
        },
        active: function () {  //所有字体已渲染
          fontLoaded();
        },
        inactive: function () { //字体预加载失败，无效字体或浏览器不支持加载
          console.log('inactive: timeout');
          fontLoaded();
        },
        timeout: 5000 // Set the timeout to two seconds
      });
    }
  }

  function asyncErr(){
    console.warn('script load from CDN failed, will load local script')
  }

  // load webfont-loader async, and add callback function
  function async(u, cb, err) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (cb) { o.addEventListener('load', function (e) { cb(null, e); }, false); }
    if (err) { o.addEventListener('error', function (e) { err(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }

  var asyncLoadWithFallBack = function(arr, success, reject) {
      var currReject = function(){
        reject()
        arr.shift()
        if(arr.length)
          async(arr[0], success, currReject)
        }

      async(arr[0], success, currReject)
  }

  asyncLoadWithFallBack([
    "https://cdn.jsdelivr.net/npm/webfontloader@1.6.28/webfontloader.min.js", 
    "https://cdn.bootcss.com/webfont/1.6.28/webfontloader.js",
    "/lib/webfontloader.min.js"
  ], asyncCb, asyncErr)
</script>        
        <img class="loading" src="/assets/loading.svg" style="display: block; margin: 6rem auto 0 auto; width: 6rem; height: 6rem;" />
        <div class="container container-unloaded">
            <main class="main post-page">
    <article class="article-entry">
        <p>torch.nn其是专门为深度学习而设计的模块。torch.nn的核心数据结构是<code>Module</code>，它是一个抽象概念，既可以表示神经网络中的某个层（layer），也可以表示一个<strong>包含很多层的神经网络</strong>。在实际使用中，最常见的做法是继承<code>nn.Module</code>，撰写自己的网络/层。</p>
<p><strong>本节主要参考资料为：<strong>apacheCN的<a href="https://pytorch.apachecn.org/docs/1.2/" target="_blank" rel="noopener">pytorch文档</a>、ShusenTang改写的pytorch版<a href="http://tangshusen.me/Dive-into-DL-PyTorch/#/" target="_blank" rel="noopener" title="《动手学深度学习》">《动手学深度学习》</a>和陈云的<a href="https://github.com/chenyuntc/pytorch-book" target="_blank" rel="noopener">《深度学习框架PYTORCH入门与实践》</a>，其中首推</strong>ShusenTang改写的pytorch版<a href="http://tangshusen.me/Dive-into-DL-PyTorch/#/" target="_blank" rel="noopener" title="《动手学深度学习》">《动手学深度学习》</a></strong>，内容详实，细节很全！</p>
<h2 id="我的github"><a class="markdownIt-Anchor" href="#我的github"></a> 我的Github</h2>
<p>为了不占篇幅，只有部分代码贴在了博客里，全部的代码在我的github库里<a href="https://github.com/xiuzheDorothy/DL_exercise" target="_blank" rel="noopener" title="here">here</a></p>
<h2 id="第一节构造模型的方法"><a class="markdownIt-Anchor" href="#第一节构造模型的方法"></a> 第一节：构造模型的方法</h2>
<p>torch.nn其是专门为深度学习而设计的模块。torch.nn的核心数据结构是<code>Module</code>，它是一个抽象概念，既可以表示神经网络中的某个层（layer），也可以表示一个<strong>包含很多层的神经网络</strong>。在实际使用中，最常见的做法是继承<code>nn.Module</code>，撰写自己的网络/层。<br />
<code>Module</code>类有三个子类</p>
<ul>
<li><strong>Sequential类：<strong>接收一个子模块的</strong>有序字典（OrderedDict）或者一系列子模块作为参数</strong>来逐一添加<code>Module</code>的实例，而模型的前向计算就是将这些实例按添加的顺序逐一计算。</li>
<li>**ModuleList类：**接收一个子模块的列表作为输入，然后也可以类似List那样进行append和extend操作。</li>
<li><strong>ModuleDict类：<strong>接收一个子模块的字典作为输入, 然后也可以</strong>类似字典那样</strong>进行添加访问操作。</li>
</ul>
<p>以上子类均可以快捷的实现简单的模型构造，且不需要够自己创建forward函数，但<strong>直接继承Module类可以极大地拓展模型构造的灵活性</strong></p>
<h2 id="第二节模型参数"><a class="markdownIt-Anchor" href="#第二节模型参数"></a> 第二节：模型参数</h2>
<h3 id="访问模型的参数"><a class="markdownIt-Anchor" href="#访问模型的参数"></a> 访问模型的参数</h3>
<p>对于<code>Sequential</code>实例中含模型参数的层，我们可以通过<code>Module</code>类的<code>parameters()</code>或者<code>named_parameters</code>方法来访问所有参数（以迭代器的形式返回），后者除了返回参数Tensor外还会返回其名字。</p>
<p>对于使用<code>Sequential</code>类构造的神经网络，我们可以通过<font color=red>方括号[ ]</font>来访问网络的任一层。<strong>索引0表示隐藏层为Sequential实例最先添加的层。</strong></p>
<p>返回的<code>param</code>的类型为<code>torch.nn.parameter.Parameter</code>，其实这是<code>Tensor</code>的子类，和Tensor不同的是如果一个Tensor是Parameter，那么它会自动被添加到模型的参数列表里</p>
<h3 id="初始化模型参数"><a class="markdownIt-Anchor" href="#初始化模型参数"></a> 初始化模型参数</h3>
<p>PyTorch的init模块里提供了多种预设的初始化方法。在下面的例子中，我们将权重参数初始化成均值为0、标准差为0.01的正态分布随机数，并依然将偏差参数清零</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> name,param <span class="keyword">in</span> net.named_parameters():</span><br><span class="line">    <span class="keyword">if</span> <span class="string">'weight'</span> <span class="keyword">in</span> name:</span><br><span class="line">        init.normal_(param,mean=<span class="number">0</span>,std=<span class="number">0.01</span>)   <span class="comment"># init.normal_(tensor, mean=0.0, std=1.0) </span></span><br><span class="line">        <span class="comment"># 第一个参数是Tensor</span></span><br><span class="line">        print(name,param.data)</span><br><span class="line"><span class="comment"># 初始化偏置</span></span><br><span class="line"><span class="keyword">for</span> name,param <span class="keyword">in</span> net.named_parameters():</span><br><span class="line">    <span class="keyword">if</span> <span class="string">'bias'</span> <span class="keyword">in</span> name:</span><br><span class="line">        init.constant_(param,val=<span class="number">0</span>)<span class="comment"># Fills the input Tensor with the value :math:`\text&#123;val&#125;`.</span></span><br><span class="line">        print(name,param.data)</span><br></pre></td></tr></table></figure>
<h3 id="自定义初始化方法"><a class="markdownIt-Anchor" href="#自定义初始化方法"></a> 自定义初始化方法</h3>
<p>有时候我们需要的初始化方法并没有在init模块中提供。这时，可以实现一个初始化方法，从而能够像使用其他初始化方法那样使用它。</p>
<p>init模块里面内嵌的初始化方法都是用inlpace方法改变Tensor值得函数，因而该过程是不记录梯度的。因而我们也可以据此自定义初始化方法</p>
<h3 id="共享模型参数"><a class="markdownIt-Anchor" href="#共享模型参数"></a> 共享模型参数</h3>
<p>在有些情况下，我们希望在多个层之间共享模型参数。之前提到了如何共享模型参数: Module类的forward函数里多次调用同一个层。此外，如果我们传入Sequential的模块是同一个Module实例的话参数也是共享的，如下例：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">linear=nn.Linear(<span class="number">1</span>,<span class="number">1</span>,bias=<span class="literal">False</span>)</span><br><span class="line">net=nn.Sequential(linear,linear)</span><br><span class="line">print(net)</span><br><span class="line"><span class="keyword">for</span> name, param <span class="keyword">in</span> net.named_parameters():</span><br><span class="line">    init.constant_(param, val=<span class="number">3</span>)</span><br><span class="line">    print(name, param.data)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 在内存中，这两个线性层其实是一个对象:</span></span><br><span class="line">print(id(net[<span class="number">0</span>]) == id(net[<span class="number">1</span>]))</span><br><span class="line">print(id(net[<span class="number">0</span>].weight) == id(net[<span class="number">1</span>].weight))</span><br></pre></td></tr></table></figure>
<p>因为模型参数里包含了梯度，所以在反向传播计算时，这些共享的参数的梯度是累加的:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">x = t.ones(<span class="number">1</span>, <span class="number">1</span>)</span><br><span class="line">y = net(x).sum()</span><br><span class="line">print(y)</span><br><span class="line">y.backward()</span><br><span class="line">print(net[<span class="number">0</span>].weight.grad) <span class="comment"># 单次梯度是3，两次所以就是6</span></span><br></pre></td></tr></table></figure>
<h2 id="第三节自定义层"><a class="markdownIt-Anchor" href="#第三节自定义层"></a> 第三节：自定义层</h2>
<p>虽然PyTorch提供了大量常用的层，但有时候我们依然希望自定义层。本节将介绍如何使用<code>Module</code>来自定义层，从而可以被重复调用</p>
<h3 id="不含模型参数的自定义层"><a class="markdownIt-Anchor" href="#不含模型参数的自定义层"></a> 不含模型参数的自定义层</h3>
<p>下面的<code>CenteredLayer</code>类通过继承<code>Module</code>类自定义了一个将输入减掉均值后输出的层，并将层的计算定义在了<code>forward</code>函数里。这个层里不含模型参数。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">CenteredLayer</span><span class="params">(nn.Module)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self,**kwargs)</span>:</span></span><br><span class="line">        super(CenteredLayer,self).__init__(**kwargs)</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">forward</span><span class="params">(self,x)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> x-x.mean()</span><br><span class="line">layer = CenteredLayer()</span><br><span class="line">layer(t.tensor([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>], dtype=t.float))</span><br></pre></td></tr></table></figure>
<h3 id="含模型参数的自定义层"><a class="markdownIt-Anchor" href="#含模型参数的自定义层"></a> 含模型参数的自定义层</h3>
<p>Parameter类是Tensor的子类，如果一个Tensor是Parameter，那么它会自动被添加到模型的参数列表里。<strong>所以在自定义含模型参数的层时，我们应该将参数定义成Parameter</strong>，除了像4.2.1节那样直接定义成Parameter类外，还可以使用ParameterList和ParameterDict分别定义参数的列表和字典。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyListDense</span><span class="params">(nn.Module)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        super(MyListDense, self).__init__()</span><br><span class="line">        self.params = nn.ParameterList([nn.Parameter(t.randn(<span class="number">4</span>, <span class="number">4</span>)) <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">3</span>)])</span><br><span class="line">        self.params.append(nn.Parameter(t.randn(<span class="number">4</span>,<span class="number">1</span>)))</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">forward</span><span class="params">(self, x)</span>:</span></span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> range(len(self.params)):</span><br><span class="line">            x = t.mm(x, self.params[i])</span><br><span class="line">        <span class="keyword">return</span> x</span><br><span class="line">net = MyDense()</span><br><span class="line">print(net)</span><br></pre></td></tr></table></figure>
<p>而<code>ParameterDict</code>接收一个<code>Parameter</code>实例的字典作为输入然后得到一个参数字典，然后可以按照字典的规则使用了。例如使用<code>update()</code>新增参数，使用<code>keys()</code>返回所有键值，使用<code>items()</code>返回所有键值对等等</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyDictDense</span><span class="params">(nn.Module)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        super(MyDictDense, self).__init__()</span><br><span class="line">        self.params = nn.ParameterDict(&#123;</span><br><span class="line">                <span class="string">'linear1'</span>: nn.Parameter(t.randn(<span class="number">4</span>, <span class="number">4</span>)),</span><br><span class="line">                <span class="string">'linear2'</span>: nn.Parameter(t.randn(<span class="number">4</span>, <span class="number">1</span>))</span><br><span class="line">        &#125;)</span><br><span class="line">        self.params.update(&#123;<span class="string">'linear3'</span>: nn.Parameter(t.randn(<span class="number">4</span>, <span class="number">2</span>))&#125;) <span class="comment"># 新增</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">forward</span><span class="params">(self, x, choice=<span class="string">'linear1'</span>)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> torch.mm(x, self.params[choice])</span><br><span class="line"></span><br><span class="line">net = MyDictDense()</span><br><span class="line">print(net)</span><br></pre></td></tr></table></figure>
<p>我们也可以使用自定义层构造模型。它和PyTorch的其他层在使用上很类似。</p>
<h2 id="总结"><a class="markdownIt-Anchor" href="#总结"></a> 总结</h2>
<p>本章的学习面临一个问题，nn里的各种操作太多，彼此之间又很孤立，如果不多上手实例就很难牢记和掌握应用，所以我在本节的做法是快速过一遍留个印象，快速进入pytorch卷积神经网络的学习然后着手复现论文或看已经成型的CNN代码</p>

    </article>
    <!-- license  -->
    
        <div class="license-wrapper">
            <p>原文作者：<a href="http://xiuzhedorothy.gitee.io">宇航猫休蛰</a>
            <p>原文链接：<a href="http://xiuzhedorothy.gitee.io/2020/02/01/pytorch-xue-xi-di-san-ke-shen-jing-wang-luo-gong-ju-xiang-torch-nn/">http://xiuzhedorothy.gitee.io/2020/02/01/pytorch-xue-xi-di-san-ke-shen-jing-wang-luo-gong-ju-xiang-torch-nn/</a>
            <p>发表日期：<a href="http://xiuzhedorothy.gitee.io/2020/02/01/pytorch-xue-xi-di-san-ke-shen-jing-wang-luo-gong-ju-xiang-torch-nn/">February 1st 2020, 4:40:09 pm</a>
            <p>更新日期：<a href="http://xiuzhedorothy.gitee.io/2020/02/01/pytorch-xue-xi-di-san-ke-shen-jing-wang-luo-gong-ju-xiang-torch-nn/">March 1st 2020, 9:22:28 pm</a>
            <p>版权声明：本文采用<a rel="license noopener" href="http://creativecommons.org/licenses/by-nc/4.0/" target="_blank">知识共享署名-非商业性使用 4.0 国际许可协议</a>进行许可</p>
        </div>
    
    <!-- paginator  -->
    <ul class="post-paginator">
        <li class="next">
            
                <div class="nextSlogan">Next Post</div>
                <a href= "/2020/02/10/chong-xin-ren-shi-anaconda/" title= "重新认识Anaconda">
                    <div class="nextTitle">重新认识Anaconda</div>
                </a>
            
        </li>
        <li class="previous">
            
                <div class="prevSlogan">Previous Post</div>
                <a href= "/2020/01/31/python-hui-gu-zhi-lei-yu-dui-xiang/" title= "python回顾之类与对象">
                    <div class="prevTitle">python回顾之类与对象</div>
                </a>
            
        </li>
    </ul>
    <!-- 评论插件 -->
    <!-- 来必力City版安装代码 -->

<!-- City版安装代码已完成 -->
    
    
    <!-- gitalk评论 -->

    <!-- utteranc评论 -->

    <!-- partial('_partial/comment/changyan') -->
    <!--PC版-->


    
    

    <!-- 评论 -->
</main>
            <!-- profile -->
            
        </div>
        <footer class="footer footer-unloaded">
    <!-- social  -->
    
    <div class="social">
        
    
        
            
                <a href="mailto:820915112@qq.com" class="iconfont-archer email" title=email ></a>
            
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    

    </div>
    
    <!-- powered by Hexo  -->
    <div class="copyright">
        <span id="hexo-power">Powered by <a href="https://hexo.io/" target="_blank">Hexo</a></span><span class="iconfont-archer power">&#xe635;</span><span id="theme-info">theme <a href="https://github.com/fi3ework/hexo-theme-archer" target="_blank">Archer</a></span>
    </div>
    <!-- 不蒜子  -->
    
    <div class="busuanzi-container">
    
     
    <span id="busuanzi_container_site_pv">PV: <span id="busuanzi_value_site_pv"></span> :)</span>
    
    </div>
    
</footer>
    </div>
    <!-- toc -->
    
    <div class="toc-wrapper" style=
    







top:50vh;

    >
        <div class="toc-catalog">
            <span class="iconfont-archer catalog-icon">&#xe613;</span><span>CATALOG</span>
        </div>
        <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#我的github"><span class="toc-number">1.</span> <span class="toc-text"> 我的Github</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#第一节构造模型的方法"><span class="toc-number">2.</span> <span class="toc-text"> 第一节：构造模型的方法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#第二节模型参数"><span class="toc-number">3.</span> <span class="toc-text"> 第二节：模型参数</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#访问模型的参数"><span class="toc-number">3.1.</span> <span class="toc-text"> 访问模型的参数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#初始化模型参数"><span class="toc-number">3.2.</span> <span class="toc-text"> 初始化模型参数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#自定义初始化方法"><span class="toc-number">3.3.</span> <span class="toc-text"> 自定义初始化方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#共享模型参数"><span class="toc-number">3.4.</span> <span class="toc-text"> 共享模型参数</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#第三节自定义层"><span class="toc-number">4.</span> <span class="toc-text"> 第三节：自定义层</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#不含模型参数的自定义层"><span class="toc-number">4.1.</span> <span class="toc-text"> 不含模型参数的自定义层</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#含模型参数的自定义层"><span class="toc-number">4.2.</span> <span class="toc-text"> 含模型参数的自定义层</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#总结"><span class="toc-number">5.</span> <span class="toc-text"> 总结</span></a></li></ol>
    </div>
    
    <div class="back-top iconfont-archer">&#xe639;</div>
    <div class="sidebar sidebar-hide">
    <ul class="sidebar-tabs sidebar-tabs-active-0">
        <li class="sidebar-tab-archives"><span class="iconfont-archer">&#xe67d;</span><span class="tab-name">Archive</span></li>
        <li class="sidebar-tab-tags"><span class="iconfont-archer">&#xe61b;</span><span class="tab-name">Tag</span></li>
        <li class="sidebar-tab-categories"><span class="iconfont-archer">&#xe666;</span><span class="tab-name">Cate</span></li>
    </ul>
    <div class="sidebar-content sidebar-content-show-archive">
          <div class="sidebar-panel-archives">
    <!-- 在ejs中将archive按照时间排序 -->
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    <div class="total-and-search">
        <div class="total-archive">
        Total : 33
        </div>
        <!-- search  -->
        
    </div>
    
    <div class="post-archive">
    
    
    
    
    <div class="archive-year"> 2021 </div>
    <ul class="year-list">
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">04/21</span><a class="archive-post-title" href= "/2021/04/21/ying-xiang-bian-hua-jian-ce-zong-shu/" >影像变化检测综述</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">03/19</span><a class="archive-post-title" href= "/2021/03/19/ji-qi-xue-xi-zuo-ye-xian-xing-hui-gui/" >机器学习作业：线性回归</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">03/06</span><a class="archive-post-title" href= "/2021/03/06/deep-image-prior/" >deep image prior论文笔记</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">01/24</span><a class="archive-post-title" href= "/2021/01/24/2018mcm-c-ti-zong-ti-hui-gu/" >2018MCM C题总体回顾</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">01/23</span><a class="archive-post-title" href= "/2021/01/23/shi-jian-xu-lie-fen-xi-ji-chu/" >时间序列分析基础</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">01/21</span><a class="archive-post-title" href= "/2021/01/21/cong-shu-ju-wa-jue-jing-sai-dao-mei-sai-c-ti/" >从数据挖掘竞赛到美赛C题——数据预处理与特征工程</a>
        </li>
    
    
    
    
    
        </ul>
    
    <div class="archive-year"> 2020 </div>
    <ul class="year-list">
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/21</span><a class="archive-post-title" href= "/2020/12/21/2020-mei-sai-c-ti-lun-wen-fen-xi/" >2020美赛C题论文分析</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">09/25</span><a class="archive-post-title" href= "/2020/09/25/densenet/" >DenseNet：CVPR 2017 Best Paper</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">09/17</span><a class="archive-post-title" href= "/2020/09/17/binarized-mode-seeking-for-scalable-visual-pattern-discovery-lun-wen-yue-du-bi-ji/" >Binarized Mode Seeking for Scalable Visual Pattern Discovery 论文阅读笔记</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">08/07</span><a class="archive-post-title" href= "/2020/08/07/resnet-yi-ge-shen-ke-ying-xiang-jin-hou-wang-luo-she-ji-de-wang-luo/" >ResNet:一个深刻影响今后网络设计的网络</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">07/04</span><a class="archive-post-title" href= "/2020/07/04/mu-biao-jian-ce-suan-fa-yolov3-gai-shu/" >目标检测算法YOLOv3概述</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">06/28</span><a class="archive-post-title" href= "/2020/06/28/patternnet-visual-pattern-mining-with-deep-neural-network-lun-wen-bi-ji/" >PatternNet: Visual Pattern Mining with Deep Neural Network 论文笔记</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">05/16</span><a class="archive-post-title" href= "/2020/05/16/dcgan/" >DCGAN:更容易训练的GAN</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">04/17</span><a class="archive-post-title" href= "/2020/04/17/lstm/" >LSTM：时序预测问题</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">03/29</span><a class="archive-post-title" href= "/2020/03/29/gan/" >GAN: the most interesting idea in the last ten years in ML</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">03/15</span><a class="archive-post-title" href= "/2020/03/15/2020-mei-sai-c-ti-can-sai-ji-lu/" >2020美赛C题参赛纪录</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">03/11</span><a class="archive-post-title" href= "/2020/03/11/zui-you-hua-dan-chun-xing-fa-qiu-jie-xian-xing-gui-hua/" >最优化：单纯形法求解线性规划</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">03/11</span><a class="archive-post-title" href= "/2020/03/11/zui-you-hua-shu-xue-li-lun-ji-chu/" >最优化：数学理论基础</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">03/07</span><a class="archive-post-title" href= "/2020/03/07/batch-normalization-rang-xun-lian-bian-de-geng-jia-rong-yi/" >Batch Normalization:让训练变得更加容易</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">03/02</span><a class="archive-post-title" href= "/2020/03/02/2018-mei-sai-c-ti-lun-wen-yue-du-yu-si-kao/" >2018美赛C题——论文阅读与思考</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">02/27</span><a class="archive-post-title" href= "/2020/02/27/2019-mei-sai-c-ti-lun-wen-yue-du-yu-si-kao-ii/" >2019美赛C题——论文阅读与思考（II）</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">02/25</span><a class="archive-post-title" href= "/2020/02/25/2019-mei-sai-c-ti-lun-wen-yue-du-yu-si-kao-i-1/" >2019美赛C题——论文阅读与思考（I）</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">02/18</span><a class="archive-post-title" href= "/2020/02/18/shen-jing-wang-luo-zhong-de-ji-zhi-you-hua-fang-fa/" >神经网络中的极值优化方法</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">02/16</span><a class="archive-post-title" href= "/2020/02/16/welcome-to-my-own-repository/" >Welcome to my own repository</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">02/10</span><a class="archive-post-title" href= "/2020/02/10/chong-xin-ren-shi-anaconda/" >重新认识Anaconda</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">02/01</span><a class="archive-post-title" href= "/2020/02/01/pytorch-xue-xi-di-san-ke-shen-jing-wang-luo-gong-ju-xiang-torch-nn/" >pytorch学习第三课：神经网络工具箱Torch.nn</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">01/31</span><a class="archive-post-title" href= "/2020/01/31/python-hui-gu-zhi-lei-yu-dui-xiang/" >python回顾之类与对象</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">01/31</span><a class="archive-post-title" href= "/2020/01/31/pytorch-xue-xi-di-er-ke-autograd/" >pytorch学习第二课：AutoGrad</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">01/30</span><a class="archive-post-title" href= "/2020/01/30/pytorch-xue-xi-di-yi-ke-tensor/" >pytorch学习第一课：Tensor</a>
        </li>
    
    
    
    
    
        </ul>
    
    <div class="archive-year"> Invalid date </div>
    <ul class="year-list">
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">Invalid date</span><a class="archive-post-title" href= "/2020/01/16/hello-world/" >Hello World</a>
        </li>
    
    
    
    
    
        </ul>
    
    <div class="archive-year"> 2020 </div>
    <ul class="year-list">
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">01/19</span><a class="archive-post-title" href= "/2020/01/19/qian-kui-shen-jing-wang-luo-xiao-jie/" >前馈神经网络小结</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">01/19</span><a class="archive-post-title" href= "/2020/01/19/zi-dong-ti-du-ji-suan-yu-you-hua-wen-ti/" >自动梯度计算与优化问题</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">01/16</span><a class="archive-post-title" href= "/2020/01/16/ji-qi-xue-xi-shi-zhan-di-yi-ke-knn-jin-lin-suan-fa/" >机器学习实战第一课——KNN近邻算法</a>
        </li>
    
    </div>
  </div>
        <div class="sidebar-panel-tags">
    <div class="sidebar-tags-name">
    
        <span class="sidebar-tag-name" data-tags="数学建模"><span class="iconfont-archer">&#xe606;</span>数学建模</span>
    
        <span class="sidebar-tag-name" data-tags="深度学习"><span class="iconfont-archer">&#xe606;</span>深度学习</span>
    
        <span class="sidebar-tag-name" data-tags="论文笔记"><span class="iconfont-archer">&#xe606;</span>论文笔记</span>
    
        <span class="sidebar-tag-name" data-tags="github"><span class="iconfont-archer">&#xe606;</span>github</span>
    
        <span class="sidebar-tag-name" data-tags="pytorch"><span class="iconfont-archer">&#xe606;</span>pytorch</span>
    
        <span class="sidebar-tag-name" data-tags="python"><span class="iconfont-archer">&#xe606;</span>python</span>
    
        <span class="sidebar-tag-name" data-tags="最优化理论"><span class="iconfont-archer">&#xe606;</span>最优化理论</span>
    
        <span class="sidebar-tag-name" data-tags="时间序列分析"><span class="iconfont-archer">&#xe606;</span>时间序列分析</span>
    
        <span class="sidebar-tag-name" data-tags="目标检测"><span class="iconfont-archer">&#xe606;</span>目标检测</span>
    
        <span class="sidebar-tag-name" data-tags="科学计算"><span class="iconfont-archer">&#xe606;</span>科学计算</span>
    
        <span class="sidebar-tag-name" data-tags="数据处理"><span class="iconfont-archer">&#xe606;</span>数据处理</span>
    
        <span class="sidebar-tag-name" data-tags="机器学习"><span class="iconfont-archer">&#xe606;</span>机器学习</span>
    
        <span class="sidebar-tag-name" data-tags="change detection"><span class="iconfont-archer">&#xe606;</span>change detection</span>
    
    </div>
    <div class="iconfont-archer sidebar-tags-empty">&#xe678;</div>
    <div class="tag-load-fail" style="display: none; color: #ccc; font-size: 0.6rem;">
    缺失模块。<br/>
    1、请确保node版本大于6.2<br/>
    2、在博客根目录（注意不是archer根目录）执行以下命令：<br/>
    <span style="color: #f75357; font-size: 1rem; line-height: 2rem;">npm i hexo-generator-json-content --save</span><br/>
    3、在根目录_config.yml里添加配置：
    <pre style="color: #787878; font-size: 0.6rem;">
jsonContent:
  meta: false
  pages: false
  posts:
    title: true
    date: true
    path: true
    text: false
    raw: false
    content: false
    slug: false
    updated: false
    comments: false
    link: false
    permalink: false
    excerpt: false
    categories: true
    tags: true</pre>
    </div> 
    <div class="sidebar-tags-list"></div>
</div>
        <div class="sidebar-panel-categories">
    <div class="sidebar-categories-name">
    
        <span class="sidebar-category-name" data-categories="数学建模"><span class="iconfont-archer">&#xe60a;</span>数学建模</span>
    
        <span class="sidebar-category-name" data-categories="机器学习-深度学习"><span class="iconfont-archer">&#xe60a;</span>机器学习-深度学习</span>
    
        <span class="sidebar-category-name" data-categories="编程语言"><span class="iconfont-archer">&#xe60a;</span>编程语言</span>
    
        <span class="sidebar-category-name" data-categories="最优化理论"><span class="iconfont-archer">&#xe60a;</span>最优化理论</span>
    
        <span class="sidebar-category-name" data-categories="数据处理"><span class="iconfont-archer">&#xe60a;</span>数据处理</span>
    
        <span class="sidebar-category-name" data-categories="目标检测"><span class="iconfont-archer">&#xe60a;</span>目标检测</span>
    
        <span class="sidebar-category-name" data-categories="科学计算"><span class="iconfont-archer">&#xe60a;</span>科学计算</span>
    
    </div>
    <div class="iconfont-archer sidebar-categories-empty">&#xe678;</div>
    <div class="sidebar-categories-list"></div>
</div>
    </div>
</div> 
    <script>
    var siteMeta = {
        root: "/",
        author: "宇航猫休蛰"
    }
</script>
    <!-- CDN failover -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.3.1/dist/jquery.min.js"></script>
    <script type="text/javascript">
        if (typeof window.$ === 'undefined')
        {
            console.warn('jquery load from jsdelivr failed, will load local script')
            document.write('<script src="/lib/jquery.min.js">\x3C/script>')
        }
    </script>
    <script src="/scripts/main.js"></script>
    <!-- algolia -->
    
    <!-- busuanzi  -->
    
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    
    <!-- CNZZ  -->
    
    </div>
    <!-- async load share.js -->
    
        <script src="/scripts/share.js" async></script>    
     
    </body>
</html>


